package com.hsyt.pfc.support.util;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

public class FtpUtil {
    private static final Logger logger = LoggerFactory.getLogger(FtpUtil.class);
    private FTPClient client;
    private static final int BUFF_SIZE = 1024 * 1024;

    public FtpUtil() {
        client = new FTPClient();
    }

    public boolean login(String host, int port, String username, String password, Integer ftpMode) {
        try {
            client.connect(host, port);
            client.login(username, password);
            int reply = client.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                disconnect();
                return false;
            }
            client.setBufferSize(BUFF_SIZE);
            if (ftpMode > 0) {
                return true;
            }
            client.enterLocalPassiveMode();
            return true;
        } catch (Exception e) {
            logger.error("获取文件流异常", e);
            return false;
        }
    }

    public InputStream getFileInputStreamByName(String path, String name) {
        try {
            client.changeWorkingDirectory(path);
            FTPFile[] files = client.listFiles(name);
            if (ArrayUtils.isEmpty(files)) {
                return null;
            }
            return client.retrieveFileStream(name);
        } catch (IOException e) {
            logger.error("获取文件流异常", e);
            return null;
        }
    }

    public void uploadFile(String path, String fileName, List<String> lines) {
        OutputStream out = null;
        try {
            client.changeWorkingDirectory(path);
            out = client.storeFileStream(fileName);
            IOUtils.writeLines(lines, "\n", out, "gb2312");
        } catch (IOException e) {
            logger.error("ftp文件上传异常", e);
        } finally {
            try {
                if (null != out) {
                    out.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    }

    public FTPClient getFtpClient() {
        return client;
    }

    public boolean disconnect() {
        try {
            if (null != client && client.isConnected()) {
                client.logout();
                client.disconnect();
            }
            return true;
        } catch (IOException e) {
            logger.error("ftp 退出异常", e);
            return false;
        }
    }
}
